from PyQt5.QtWidgets import (QWidget, QVBoxLayout, QPushButton, 
                           QTextEdit, QMessageBox, QLineEdit, QLabel,
                           QHBoxLayout)
from PyQt5.QtCore import QThread, pyqtSignal
from core.platform_auth import platform_auth
from core.platform_config import platform_config
import aiohttp
from loguru import logger
import asyncio

class PersonApi:
    def __init__(self):
        self.base_url = f"{platform_config.dahua.api_host}/evo-apigw"
        
    async def search_by_card(self, card_number: str) -> dict:
        """根据卡号查询人员信息"""
        try:
            headers = await platform_auth.get_dahua_headers()
            async with aiohttp.ClientSession() as session:
                url = f"{self.base_url}/evo-brm/1.2.0/person/page"
                data = {
                    "searchKey": "",
                    "pageNum": 1,
                    "pageSize": 10,
                    "departmentId": 1,
                    "isContain": True,
                    "statusList": [1, 2]
                }
                
                async with session.post(url, headers=headers, json=data, ssl=False) as response:
                    result = await response.json()
                    if not result.get("success"):
                        return None
                        
                    # 在结果中查找匹配的卡号
                    persons = result.get("data", {}).get("pageData", [])
                    for person in persons:
                        cards = person.get("cards", [])
                        for card in cards:
                            if card.get("cardNumber") == card_number:
                                return person
                    return None
                    
        except Exception as e:
            logger.exception(f"查询人员信息异常: {str(e)}")
            return None

    async def get_person_detail(self, person_id: int) -> dict:
        """获取人员详情"""
        try:
            headers = await platform_auth.get_dahua_headers()
            async with aiohttp.ClientSession() as session:
                url = f"{self.base_url}/evo-brm/1.2.0/person/{person_id}"
                async with session.get(url, headers=headers, ssl=False) as response:
                    result = await response.json()
                    if result.get("success"):
                        return result.get("data")
                    return None
        except Exception as e:
            logger.exception(f"获取人员详情异常: {str(e)}")
            return None

class AsyncHelper(QThread):
    finished = pyqtSignal()
    data_loaded = pyqtSignal(object)
    
    def __init__(self, coro):
        super().__init__()
        self.coro = coro
        self._is_running = True
        
    def run(self):
        try:
            if self._is_running:
                loop = asyncio.new_event_loop()
                asyncio.set_event_loop(loop)
                result = loop.run_until_complete(self.coro)
                loop.close()
                if self._is_running:
                    self.data_loaded.emit(result)
        except Exception as e:
            logger.exception("AsyncHelper error: %s", str(e))
        finally:
            if self._is_running:
                self.finished.emit()
    
    def stop(self):
        """停止线程"""
        self._is_running = False
        self.wait()

class ReadCardPage(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.person_api = PersonApi()
        self.current_tasks = []
        self.setup_ui()
        
    def setup_ui(self):
        layout = QVBoxLayout(self)
        
        # 卡号输入区域
        input_layout = QHBoxLayout()
        card_label = QLabel("卡号:")
        self.card_input = QLineEdit()
        self.card_input.setPlaceholderText("请输入卡号")
        input_layout.addWidget(card_label)
        input_layout.addWidget(self.card_input)
        layout.addLayout(input_layout)
        
        # 显示区域
        self.display = QTextEdit()
        self.display.setReadOnly(True)
        layout.addWidget(self.display)
        
        # 读卡按钮
        read_btn = QPushButton("读取卡片信息")
        read_btn.clicked.connect(self.read_card)
        layout.addWidget(read_btn)
        
        # 添加编辑按钮
        button_layout = QHBoxLayout()
        self.edit_btn = QPushButton("编辑信息")
        self.edit_btn.setEnabled(False)  # 初始禁用
        self.edit_btn.clicked.connect(self.edit_person)
        button_layout.addWidget(self.edit_btn)
        layout.addLayout(button_layout)
        
    def read_card(self):
        """读取卡片信息"""
        card_number = self.card_input.text().strip()
        if not card_number:
            QMessageBox.warning(self, "警告", "请输入卡号")
            return
            
        # 调用查询接口
        async_helper = AsyncHelper(self.person_api.search_by_card(card_number))
        async_helper.data_loaded.connect(self.on_card_info_loaded)
        self.current_tasks.append(async_helper)
        async_helper.finished.connect(lambda: self.current_tasks.remove(async_helper))
        async_helper.start()
        
    def on_card_info_loaded(self, person_info):
        """处理查询结果"""
        if not person_info:
            QMessageBox.warning(self, "提示", "未找到该卡号对应的人员信息")
            self.display.clear()
            self.edit_btn.setEnabled(False)
            return
            
        # 保存当前人员ID
        self.current_person_id = person_info.get('id')
        self.edit_btn.setEnabled(True)
            
        # 显示人员信息
        info_text = "卡片信息：\n"
        info_text += f"姓名: {person_info.get('name', '')}\n"
        info_text += f"部门: {person_info.get('departmentName', '')}\n"
        info_text += f"人员编号: {person_info.get('code', '')}\n"
        info_text += f"身份证号: {person_info.get('paperNumber', '')}\n"
        info_text += f"性别: {'男' if person_info.get('sex') == 1 else '女'}\n"
        info_text += f"出生日期: {person_info.get('birthday', '')}\n"
        info_text += f"年龄: {person_info.get('age', '')}岁\n"
        
        # 显示卡片信息
        cards = person_info.get("cards", [])
        if cards:
            info_text += "\n卡片列表：\n"
            for card in cards:
                info_text += f"卡号: {card.get('cardNumber', '')}\n"
                info_text += f"类型: {'主卡' if card.get('isMainCard') == 1 else '副卡'}\n"
                info_text += f"有效期: {card.get('startDate', '')} 至 {card.get('endDate', '')}\n"
                info_text += "------------------------\n"
                
        self.display.setText(info_text)
        
    def edit_person(self):
        """跳转到编辑页面"""
        if hasattr(self, 'current_person_id'):
            # 获取详细信息并跳转
            async_helper = AsyncHelper(self.person_api.get_person_detail(self.current_person_id))
            async_helper.data_loaded.connect(self.show_edit_page)
            self.current_tasks.append(async_helper)
            async_helper.finished.connect(lambda: self.current_tasks.remove(async_helper))
            async_helper.start()

    def show_edit_page(self, person_detail):
        """显示编辑页面"""
        if not person_detail:
            QMessageBox.warning(self, "错误", "获取人员详情失败")
            return
            
        if self.parent():
            # 获取InfoInputPage实例
            info_page = self.parent().widget(1)  # 假设InfoInputPage是第二个页面
            if info_page:
                # 设置详细信息
                info_page.set_person_info(person_detail)
                # 切换到编辑页面
                self.parent().setCurrentIndex(1)
        
    def closeEvent(self, event):
        """窗口关闭时清理线程"""
        for task in self.current_tasks[:]:
            task.stop()
        self.current_tasks.clear()
        super().closeEvent(event) 